package org.apache.lucene.ocean.database;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.ocean.Snapshot;
import org.apache.lucene.ocean.TransactionSystem;
import org.apache.lucene.ocean.util.Constants;
import org.apache.lucene.ocean.util.Util;

/**
 * Load a single document from the id and version
 *
 */
public class LoadObjectTask implements Task {
  long id;
  long version;
  
  public LoadObjectTask(long id, long version) {
    this.id = id;
    this.version = version;
  }
  
  public Object run(TransactionSystem transactionSystem) throws Exception {
    Snapshot snapshot = transactionSystem.getSnapshots().getLatestSnapshot();
    try {
      IndexReader reader = snapshot.getIndexReader();
      int doc = Util.getTermDoc(new Term(Constants.ID_VERSION, Util.toIdVersionString(id, version)), reader);
      if (doc > -1) {
        Document document = reader.document(doc);
        return new OceanObject(document);
      }
      return null;
    } finally {
      snapshot.decRef();
    }
  }
}
